﻿namespace Stopwatch
{
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    using System.Text;

    [DataContract]
    public abstract class JsonSerializable
    {
        protected string ToJson()
        {
            try
            {
                //Create a stream to serialize the object to.
                using (MemoryStream ms = new MemoryStream())
                {
                    // Serializer the State object to the stream.
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(GetType());
                    ser.WriteObject(ms, this);
                    byte[] json = ms.ToArray();

                    return Encoding.UTF8.GetString(json, 0, json.Length);
                }
            }
            catch { return string.Empty; }
        }
    }
}
